package movie.wrapper;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.net.URL;
import java.net.URLEncoder;
import org.json.*;
import java.io.*;

public class Methods {
	
	static final String IMDBServiceURL = "http://www.deanclatworthy.com/imdb/?q=%s&sadfkljasdflkj32123123kljjkl=1";
	
	public Movie SearchIMDB(String MovieTitle)
	{
		try
		{
			Movie movie = Caching.getInstance().Get(MovieTitle);
			
			if (movie == null)
			{
				movie = GetMovie(MovieTitle);
				Caching.getInstance().Add(movie);
			}
			else
			{
				SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");  
				Calendar cal = Calendar.getInstance();
			    Date date = dateformat.parse(movie.CachedDate);
			    cal.setTime(date);
				cal.add(Calendar.DATE, 10);
				
				if (Calendar.getInstance().after(cal))
				{
					movie = GetMovie(MovieTitle);
					Caching.getInstance().Remove(MovieTitle);
					Caching.getInstance().Add(movie);
				}
			}
			return movie;
		}
		catch(Exception e)
		{
			return new Movie(e.getMessage(),"","","","");
		}
	}
	
	private JSONObject CallIMDBService(String MovieTitle)
	{
		try
		{
			// Test - "{\"id\":\"0\",\"title\":\"Imagine That\",\"imdburl\":\"http://www.imdb.com/title/tt0780567/\",\"country\":\"USA,Germany\",\"languages\":\"English\",\"genres\":\"Comedy,Drama,Fantasy\",\"rating\":\"4.8\",\"votes\":\"1117\",\"usascreens\":3011,\"ukscreens\":0,\"year\":\"2009\",\"stv\":0,\"series\":0}";
			String json = "";
			
			URL request = new URL(String.format(IMDBServiceURL,URLEncoder.encode(MovieTitle, "utf-8")));
			BufferedReader in = new BufferedReader(
					new InputStreamReader(
							request.openStream()));
			
			json = in.readLine();
			
			in.close();
			
			return new JSONObject(json);
		}
		catch(Exception e)
		{
			return null;
		}
	}
	
	private Movie PopulateObject(JSONObject Movie)
	{
		try
		{
			String Name = Movie.getString(movie.wrapper.Movie.NameTitle);
			String URL = Movie.getString(movie.wrapper.Movie.URLTitle);
			String Genres = Movie.getString(movie.wrapper.Movie.GenresTitle);
			String Rating = String.valueOf(Movie.getInt(movie.wrapper.Movie.RatingTitle));
			String Voting = String.valueOf(Movie.getInt(movie.wrapper.Movie.VotesTitle));
			
			return new Movie(Name, URL, Genres, Rating, Voting);
		}
		catch(Exception E)
		{
			return null;
		}
	}
	
	private Movie GetMovie(String MovieTitle)
	{
		Movie movie = null;
		JSONObject imdbObj = CallIMDBService(MovieTitle);
		movie = PopulateObject(imdbObj);

		SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");  
		Calendar cal = Calendar.getInstance();
		movie.CachedDate = dateformat.format(cal.getTime());
		
		return movie;
	}
}
